package com.ty.interceptor;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter", urlPatterns = {"/index.html", "/hello"})
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpSession session = httpRequest.getSession();

        // 检查用户是否已登录
        String username = (String) session.getAttribute("username");
        if (username == null) {
            // 用户未登录，重定向到登录页面
            httpResponse.sendRedirect("login.html");
        } else {
            // 用户已登录，继续处理请求
            chain.doFilter(request, response);
        }
    }
}